package com.bluetrum.abmate.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.bluetrum.abmate.R;
import com.bluetrum.abmate.databinding.DialogFragmentNameBinding;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.nio.charset.StandardCharsets;

public class DialogFragmentDeviceName extends DialogFragment {

    private static final String DEVICE_NAME = "DEVICE_NAME";

    private static final int DEVICE_NAME_LENGTH_LIMIT = 32;

    private DialogFragmentNameBinding binding;

    TextInputLayout deviceNameInputLayout;
    TextInputEditText deviceNameInput;
    TextView alertMessage;

    private String mDeviceName;

    public static DialogFragmentDeviceName newInstance(final String deviceName) {
        DialogFragmentDeviceName fragmentDeviceName = new DialogFragmentDeviceName();
        final Bundle args = new Bundle();
        args.putString(DEVICE_NAME, deviceName);
        fragmentDeviceName.setArguments(args);
        return fragmentDeviceName;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mDeviceName = getArguments().getString(DEVICE_NAME);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        binding = DialogFragmentNameBinding.inflate(LayoutInflater.from(getContext()));

        deviceNameInputLayout = binding.textInputLayout;
        deviceNameInput = binding.textInput;
        alertMessage = binding.alertMessage;

        final TextView summary = binding.summary;
        deviceNameInputLayout.setHint(getString(R.string.hint_friendly_name));
        // Uncomment to use only alphabet, number and ('-' & '_')
//        deviceNameInput.setKeyListener(new DeviceNameKeyListener());
        deviceNameInput.setText(mDeviceName);
        deviceNameInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    deviceNameInputLayout.setError(getString(R.string.error_empty_name));
                } else {
                    deviceNameInputLayout.setError(null);
                }
                // 限制设备名称长度
                int nameLength = s.toString().getBytes(StandardCharsets.UTF_8).length;
                if (nameLength > DEVICE_NAME_LENGTH_LIMIT) {
                    alertMessage.setText(R.string.device_name_length_exceeded);
                } else {
                    alertMessage.setText(null);
                }
            }

            @Override
            public void afterTextChanged(final Editable s) {

            }
        });

        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(requireContext()).setView(binding.getRoot())
                .setPositiveButton(R.string.ok, null).setNegativeButton(R.string.cancel, null);

        alertDialogBuilder.setTitle(R.string.title_device_name);
        summary.setText(R.string.device_name_rationale);

        final AlertDialog alertDialog = alertDialogBuilder.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
            final String deviceName = deviceNameInput.getEditableText().toString().trim();
            if (!TextUtils.isEmpty(deviceName) && deviceName.length() <= DEVICE_NAME_LENGTH_LIMIT) {
                // 如果ParentFragment实现了DialogFragmentDeviceNameListener接口，则调用ParentFragment的
                if (requireParentFragment() instanceof DialogFragmentDeviceNameListener) {
                    if (((DialogFragmentDeviceNameListener) requireParentFragment()).onDeviceNameUpdated(deviceName)) {
                        dismiss();
                    }
                }
                // 如果FragmentActivity实现了DialogFragmentDeviceNameListener接口，则调用FragmentActivity的
                else if (requireActivity() instanceof DialogFragmentDeviceNameListener) {
                    if (((DialogFragmentDeviceNameListener) requireActivity()).onDeviceNameUpdated(deviceName)) {
                        dismiss();
                    }
                }
            }
        });

        return alertDialog;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public interface DialogFragmentDeviceNameListener {
        boolean onDeviceNameUpdated(@NonNull final String deviceName);
    }
}
